package cn.tedu.coolshark.filter;

import cn.tedu.coolshark.pojo.vo.UserVo;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "MyFilter",
        urlPatterns = {"/admin.html","/insertBanner.html"})
public class MyFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        //因为要用到子类里面的属性或方法 所以进行类型强转
        HttpServletRequest req=(HttpServletRequest) request;
        HttpServletResponse res=(HttpServletResponse) response;
        //得到Session对象
        HttpSession session=req.getSession();
        //从Session里面获取登录成功是保存的用户对象
        UserVo user=(UserVo) session.getAttribute("user");
        if(user==null){//未登录
            res.sendRedirect("/login.html");//让客服端重定向到登录页面
        }else {//登录过
            chain.doFilter(request,response);//放行  允许访问资源
        }

        chain.doFilter(request, response);//放行 允许访问资源
    }
}
